<?php
/**
 * Obsługa bazy danych
 * @author Miron Pawlik
 */
class dbHandler extends PDO {
    private $dbPDO;

    /**
     * dbHandler construct
     *
     * @access public
     * @param string $sqlite_file path to database file
     */
    public function __construct( $sqliteFile ) {
        try {
            parent::__construct('sqlite:'.$sqliteFile);
            $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $e) {
            die($e);
        }
    }
    /**
     * return last error
     * @return string
     */
    public function error() {
        return errorInfo();
    }

    /**
     * return a row, with chosen identity
     *
     * @param int|string $id record identity
     * @param string $table sql table
     * @param string $what which fiels should be return
     * @param string $field which column is identity
     * @return array
     */
    public function getById($id, $table, $what = '*', $field = 'id') {
        $shtm = $this->prepare('SELECT '.$what.' FROM '.$table.' WHERE `'.$field.'` = :id');
        $shtm->bindValue(':id', $id);
        $shtm->execute();
        return $shtm->fetch();
    }

    /**
     * deleting rows from table, with getting id
     * @param int|string $id
     * @param string $table
     * @param string $field
     * @return boolean
     */
    public function delById( $id , $table , $field = 'id') {
        $query = $this->prepare("DELETE FROM `$table` WHERE `$field` = :id");
        $query->bindValue(':id', $id);
        return $query->execute();
    }

    /**
     * edit rows, that have chosen identity
     *
     * @param int|string $id
     * @param string $table
     * @param array &$data keys are names of fields. Array values.
     * @param string $field
     * @return boolean
     */
    public function editById( $id , $table , array $data , $field = 'id' ) {
        $str = "";
        foreach( $data as $k => $v ) {
            $str .= '`'.$k.'` = :'.$k.',';
        }
        $str = substr($str, 0, -1);
        $query = $this->prepare("UPDATE `$table` SET $str WHERE `$field` = :id");
        $query->bindValue(':id', $id);
        foreach($data as $k => $v) {
            $query->bindValue(':'.$k, $v);
        }
        return $query->execute();
    }

    /**
     * adding new record
     *
     * id field are adding automatically
     *
     * @param string $table
     * @param array &$data keys are names of fields. Array values.
     * @return boolean
     */
    public function addNew( $table , array $data ) {
    $key = '';
    $val = '';
        foreach( $data as $k => $v ) {
            $key .= " `$k`,";
            $val .= " :$k,";
        }
        $query = $this->prepare("INSERT INTO $table (".substr($key, 0, -1).") VALUES (".substr($val, 0, -1).")");
        foreach($data as $k => $v) {
            $query->bindValue(':'.$k, $v);
        }
        return $query->execute();
    }

    /**
     * adding or editing record (depend on $id param)
     *
     * @param string $table
     * @param array &$data keys are names of fields. Array values.
     * @return boolean
     */
    public function takeRecord( $table , array $data , $id = false ) {
        if( $id )
            return $this->editById( $id , $table , $data );
        else
            return $this->addNew( $table , $data );
    }

    /**
     * return all rows that comply with conditions
     *
     * @param string $table
     * @param string $order
     * @param string $cond
     * @param string $limit
     * @return array
     */
    public function getAll($table , $order = false, $cond = false, $limit = false, $fields = false) {
        $order = ($order) ? "ORDER BY $order" : "";
        $cond = ($cond) ? "WHERE $cond" : "";
        $limit = ($limit) ? "LIMIT $limit" : "";
        $fields = ($fields) ? $fields : "*";
        $result = $this->query( "SELECT $fields FROM $table $cond $order $limit" );
        $tmp = $result->fetchAll();
        $result->closeCursor();
        return $tmp;
    }

    /**
     * deleting all records, comply with conditions
     * @param string $table
     * @param string $cond
     * @param string $limit
     * return resource
     */
    public function deleteAll($table , $cond = false, $limit = false) {
        $cond = ($cond) ? "WHERE $cond" : "";
        $limit = ($limit) ? "LIMIT $limit" : "";
        return $this->exec( "DELETE FROM $table $cond $limit" );
    }

    /**
     *  return maximal id from table
     * @deprecated
     * @param string $table
     * @param string $field
     * @return int
     */
    public function LastId( $table , $field = 'id') {
        $query = $this->query( "SELECT $field FROM $table ORDER BY $field DESC LIMIT 0,1" );
        $result = $query->fetch( );
        $query->closeCursor();
        return $result[$field];
    }
    /**
     * return number of rows, that comply with conditions
     * @param string $table
     * @param string $cond
     * @return int
     */
    public function CountRec($table, $cond = "") {
        $cond = ($cond == "")? "": " WHERE ".$cond;
        $result = $this->query( "SELECT COUNT(*) as ile FROM ". $table.$cond );
        $tmp = $result->fetch();
        $result->closeCursor();
        return $tmp['ile'];
    }

    //funkcja wczytujaca conig (lub inne dane) do tablicy
    /**
     * return data table
     * @param string $table
     * @param string $cond
     * @param string $name
     * @param string $value
     * @return int
     */
    public function getData($table, $cond = false, $name = 'name', $value = 'value') {
        $cond = ($cond) ? "WHERE $cond" : "";
        $result = $this->query( "SELECT * FROM $table $cond" );
        $conf = array();
        while($t = $result->fetch())
            $conf[($t[$name])] = $t[$value];
        $result->closeCursor();
        return $conf;
    }

}
